package cn.wing.gson;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.item.ItemStack;

import java.io.IOException;

public class ItemStackTypeAdapter extends TypeAdapter<ItemStack> {

    @Override
    public void write(JsonWriter out, ItemStack value) throws IOException {
        if (value == null || value.isEmpty()) {
            out.nullValue();
            return;
        }
        CompoundTag nbt = value.save(new CompoundTag());
        out.value(nbt.toString());          // 写成 NBT 字符串
    }

    @Override
    public ItemStack read(JsonReader in) throws IOException {
        String str = in.nextString();
        try {
            CompoundTag nbt = CompoundTag.CODEC.parse(com.mojang.serialization.JsonOps.INSTANCE,
                    com.google.gson.JsonParser.parseString(str)).getOrThrow(false, s -> {});
            return ItemStack.of(nbt);       // 还原 ItemStack
        } catch (Exception e) {
            return ItemStack.EMPTY;
        }
    }
}